package db

import (
	"apibe/grpc/rome/v1/share/config"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

const (
	CollectionDesign      = "design"
	CollectionDesignWatch = "watch"
	CollectionUser        = "user"
	CollectionTask        = "task"
	CollectionLogger      = "logger"
)

var mgo *mongo.Database

func GetMongoCollection(collection string) *mongo.Collection {
	return mgo.Collection(collection)
}

func mongoInit() {
	timeout := time.Second * 30
	var maxPoolSize uint64 = 100
	var minPoolSize uint64 = 20
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	o := options.Client().ApplyURI(config.Config.Mongo.Url)
	o.SetMinPoolSize(minPoolSize)
	o.SetMaxPoolSize(maxPoolSize)
	client, err := mongo.Connect(ctx, o)
	if err != nil {
		panic(err.Error())
	}
	mgo = client.Database(config.Config.Mongo.DB)
	// 创建索引
	createIndexs()
}

func createIndexs() {
	designModel := []mongo.IndexModel{
		{Keys: bson.M{"api_name": int32(1)}, Options: options.Index().SetUnique(true)},
		{Keys: bson.M{"group_name": int32(1)}},
	}
	_, err := mgo.Collection(CollectionDesign).Indexes().CreateMany(context.Background(), designModel)

	userModel := mongo.IndexModel{
		Keys:    bson.M{"account": int32(1)},
		Options: options.Index().SetUnique(true), // 唯一索引
	}
	_, err = mgo.Collection(CollectionUser).Indexes().CreateOne(context.Background(), userModel)

	loggerModel := mongo.IndexModel{
		Keys:    bson.M{"time": int32(-1)},
		Options: options.Index().SetExpireAfterSeconds(365 * 24 * 3600), // 失效时间是365天
	}
	_, err = mgo.Collection(CollectionLogger).Indexes().CreateOne(context.Background(), loggerModel)

	if err != nil {
		panic(err)
	}
}
